package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.constant.CacheKey;
import com.robotserver.orders.entity.ElmOrders;
import com.robotserver.orders.entity.TbOrders;
import com.robotserver.orders.mapper.ElmOrdersMapper;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.param.ElmOrderSyncParam;
import com.robotserver.orders.param.ElmOrderSyncParamV3;
import com.robotserver.orders.param.TbOrderSyncParam;
import com.robotserver.orders.param.TbOrderSyncParamV3;
import com.robotserver.orders.param.biz.ElmOrderPullParam;
import com.robotserver.orders.param.biz.TbOrderPullParam;
import com.robotserver.orders.service.ElmOrderService;
import com.robotserver.orders.service.ElmOrderSyncService;
import com.robotserver.orders.vo.ElmOrderTimeVO;
import com.robotserver.orders.vo.TbkOrderTimeVO;
import com.robotserver.orders.vo.biz.ElmOrderVO;
import com.robotserver.orders.vo.biz.PageVO;
import com.robotserver.orders.vo.biz.TbOrderVO;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2019/11/13 17:05
 * @Description:
 */
@Service
public class ElmOrderServiceImpl implements ElmOrderService {

    private static Logger logger = LoggerFactory.getLogger(ElmOrderServiceImpl.class);

    @Autowired
    private ElmOrderSyncService elmOrderSyncService;
    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private ElmOrdersMapper elmOrdersMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${elm.sdk.url}")
    private String elmSdkUrl;

    @Override
    public PageVO getOrderList(ElmOrderPullParam param) {
        List<ElmOrders> list = elmOrdersMapper.getOrderList(param);
        ElmOrderVO elmOrderVO = new ElmOrderVO();
        elmOrderVO.setRecords(list);
        return elmOrderVO;
    }

    @Override
    public PageVO getOrderListNew(ElmOrderPullParam param) {
        List<ElmOrders> list = elmOrdersMapper.getOrderListNew(param);
        ElmOrderVO elmOrderVO = new ElmOrderVO();
        elmOrderVO.setRecords(list);
        return elmOrderVO;
    }

    @Override
    public List<ElmOrders> getByParentOrderId(String orderId) {
        return elmOrdersMapper.getByParentOrderId(orderId);
    }

    @Override
    public ElmOrders getByParentOrderId(String parentOrderId, String bizOrderId) {
        return elmOrdersMapper.getByParAndCliId(parentOrderId, bizOrderId);
    }

    /**
     * 通过工具商获取饿了么订单
     */
    @Async("taskExecutor")
    @Override
    public void syncOrder_byAppKey(ElmOrderSyncParam elmOrderSyncParam) {
        List<ElmOrderTimeVO> elmOrderTimeScope = DateUtil.getElmOrderTimeScope_ByAppKey(elmOrderSyncParam.getBegin_time(),elmOrderSyncParam.getEnd_time());
        String elm_appkeys = sysSettingMapper.getByKey("elm_appkey");
        String elm_appsecrets = sysSettingMapper.getByKey("elm_appsecret");

        //随机取一个
//        String[] aks = getAppkey(elm_appkeys, elm_appsecrets);
//        String elm_appkey = aks[0];
//        String elm_appsecret = aks[1];
//        ElmClient client = new DefaultElmClient(elmSdkUrl,"",elm_appkey,elm_appsecret,5000,5000);

        //二个都要拉取
        String[] elmAppKeyArr = elm_appkeys.split(",");
        String[] elmAppsecretArr = elm_appsecrets.split(",");

        logger.info("---------饿了么通过工具商AppKey拉取订单-------开始------");

        if(elmAppKeyArr != null && elmAppsecretArr != null && elmAppKeyArr.length == elmAppsecretArr.length) {
            for (int i = 0; i < elmAppKeyArr.length; i++) {
                try {
                    TaobaoClient client = new DefaultTaobaoClient(elmSdkUrl, "", elmAppKeyArr[i], elmAppsecretArr[i] ,5000,5000);
                    elmOrderSyncService.threadSyncOrder_byAppKey(elmOrderTimeScope, client, elmOrderSyncParam.getDownTimeType());
                }catch (Exception e){
                    logger.error("---饿了么通过工具商下载失败，elmAppKey={},elmAppsecret={}", elmAppKeyArr[i], elmAppsecretArr[i]);
                }
            }
        }
        logger.info("---------饿了么通过工具商AppKey拉取订单-------结束----");
    }

    /**
     * 补单拉取饿了么订单-生产者-往redis队列当中生产
     */
    @Async("taskExecutor")
    @Override
    public void syncOrder_byAppKey_producer(ElmOrderSyncParam elmOrderSyncParam) {
        List<ElmOrderTimeVO> elmOrderTimeScope = DateUtil.getElmOrderTimeScope_ByAppKey(elmOrderSyncParam.getBegin_time(), elmOrderSyncParam.getEnd_time());
        //对象转成JSON字符串，保存到redis队列中
        //往redis队列中塞阿里妈妈tokens
        if(elmOrderTimeScope != null && elmOrderTimeScope.size() > 0){
            for (ElmOrderTimeVO elmOrderTimeVO : elmOrderTimeScope) {
                elmOrderTimeVO.setDownTimeType(elmOrderSyncParam.getDownTimeType());
                String elmOrderTimeVOStr = JSONObject.toJSONString(elmOrderTimeVO);
                redisTemplate.opsForList().leftPush(CacheKey.elmAppkeyOrderQueue, elmOrderTimeVOStr);
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void syncOrder_byAppKey_consumer(ElmOrderSyncParam elmOrderSyncParam) {

        String elm_appkeys = sysSettingMapper.getByKey("elm_appkey");
        String elm_appsecrets = sysSettingMapper.getByKey("elm_appsecret");

        //二个都要拉取
        String[] elmAppKeyArr = elm_appkeys.split(",");
        String[] elmAppsecretArr = elm_appsecrets.split(",");

        while (true) {
            try {
                //从redis队列中获取联盟
                Object elmTokensObject = redisTemplate.opsForList().rightPop(elmOrderSyncParam.getRedisQueueKey());
                if (elmTokensObject != null) {
                    if(elmAppKeyArr != null && elmAppsecretArr != null && elmAppKeyArr.length == elmAppsecretArr.length){
                        for (int i = 0; i < elmAppKeyArr.length; i++) {
                            try {
                                TaobaoClient client = new DefaultTaobaoClient(elmSdkUrl, elmAppKeyArr[i], elmAppsecretArr[i]);
                                ElmOrderTimeVO elmOrderTimeVO = JSONObject.parseObject(elmTokensObject.toString(),ElmOrderTimeVO.class);

                                Integer downTimeType = elmOrderTimeVO.getDownTimeType();
                                if(downTimeType == null){
                                    downTimeType = 4; //订单更新时间
                                }
                                elmOrderSyncService.threadSyncElmOrder_byAppKey_consumer(elmOrderTimeVO,client, downTimeType);
                                //暂停10毫秒
                                Thread.sleep(10);
                            }catch (Exception e){
                                // 没有需要处理的数据了
                                logger.error("--补拉饿了么通过工具商下载订单出错--elmAppKey={},elmAppsecret={}", elmAppKeyArr[i], elmAppsecretArr[i]);
                            }
                        }
                    }
                }else{
                    // 没有需要处理的数据了
                    logger.info("-------------------------补拉饿了么Redis队列已经消费完成---------------！");
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
